<template>

<move-base class="draggable_son" message="X1"
    :style="{ top: boxTop + 'px', left: boxLeft + 'px' }"
    @mousedown="dragStart"
    @touchstart="dragStart"></move-base>

<!-- <div class="son">
</div>
<div class="draggable">
    拖动我
</div> -->

</template>



<script>
import MoveBase from './MoveBase.vue';

export default {
  data() {
    return {
        dragging: false,
        boxTop: 0,
        boxLeft: 0,
        mouseOffset: { x: 0, y: 0 },
    }
  },
  methods: {
    dragStart(e) {
      e.preventDefault();
      this.dragging = true;
      const rect = e.target.getBoundingClientRect();
      this.mouseOffset.x = e.clientX - rect.left;
      this.mouseOffset.y = e.clientY - rect.top;
    //   this.mouseOffset.x = e.clientX ;
    //   this.mouseOffset.y = e.clientY ;

      console.log("mouseOffset.x=" + this.mouseOffset.x);
      console.log("mouseOffset.y=" + this.mouseOffset.y);

      document.addEventListener('mousemove', this.drag);
      document.addEventListener('touchmove', this.drag);
      document.addEventListener('mouseup', this.dragEnd);
      document.addEventListener('touchend', this.dragEnd);
    },
    drag(e) {
      if (this.dragging) {
        const mousePos = { x: e.clientX, y: e.clientY };
        this.boxTop = mousePos.y - this.mouseOffset.y;
        this.boxLeft = mousePos.x - this.mouseOffset.x;

        console.log("boxTop=" + this.boxTop);
        console.log("boxLeft=" + this.boxLeft);

      }
    },
    dragEnd() {
      this.dragging = false;
      document.removeEventListener('mousemove', this.drag);
      document.removeEventListener('touchmove', this.drag);
      document.removeEventListener('mouseup', this.dragEnd);
      document.removeEventListener('touchend', this.dragEnd);
    },
  },
  components: {
    'move-base': MoveBase,
  }
}
</script>

<style>
.draggable_son {
    margin-left: 50px;
    margin-top: 50px;
  position: absolute;
  z-index: 9;
}
.draggable {
  position: absolute;
  width: 100px;
  height: 100px;
  cursor: pointer;
  background-color: #460eaf;
  color: white;
  text-align: center;
  line-height: 100px;
  border-radius: 5px;
  z-index: 10;
}
.son{
    position: static;
    /* margin-left: 50px;
    margin-top: 50px; */
    width: 50px;
    height: 50px;
    background-color: red;
    z-index: 12;
}
</style>
